<?php

namespace App\Http\Controllers\Business;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;
class GoodsController extends Controller
{
    //add
    public function add()		
    {
        // 查找父类
        $goods = DB::table('goods')
            -> select(['id','proname','path','pid',DB::raw("concat(path,',',id) as sort")])
            -> where('cateid',62)//$session['cateid'];
            ->orderBy ('sort','asc')
            ->get();
        
        foreach($goods as $k => $v)
        {
            $count = substr_count($v -> path,',');
            $str = str_repeat('|-------',$count);

            $goods[$k] -> proname = $str.$v -> proname;
            
        }
    	// // 查找祖类
    	// $cates = DB::table('cates')
    	// 	-> select(['id','name','path',DB::raw("concat(path,',',id) as sort")])
    	// 	-> where('id',9)
     //        ->orderBy ('sort','asc')
    	// 	->get();
    		
    	// foreach($cates as $k => $v)
    	// {
    	// 	$count = substr_count($v -> path,',');
    	// 	$str = str_repeat('|-------',$count);

    	// 	$cates[$k] -> name = $str.$v -> name;
    	// 	//讲逗号个数加入到数组中传递到前台
    	// 	$cates[$k] -> count =$count;
    	// }

    	
    	

    	return view('business.goods.add',['goods' => $goods]);
    }

    //insert
    public function insert(Request $request)
    {

    	//验证错误
    	$this -> validate($request,[

    		'proname' => 'required',
    		'pid'=> 'required',
    		
    		],[
    		'proname.required'=>'商品名不能为空',
    		'pid.required'=>'父类不能为空',
    		
    		]);
    	$data = $request -> except('_token');
    	if($data['pid'] == 0)
    	{
    		$data['path'] = 0;
    	}else
    	{
    		$data['path'] = '0'.','.$data['pid'];
    	}

    	//处理图片
    	//判断图片是否上传
    	if($request -> hasFile('image'))
    	{

    		//判断图片是否有效
    		if($request -> file('image') -> isValid())
    		{
    			//获取扩展名
    			$suffix = $request -> file('image') -> getClientOriginalExtension();
    			//随机名称
    			$fileName = time().mt_rand(100000,999999).'.'.$suffix;
    			//移动位置
    			$request -> file('image') -> move('./uploads',$fileName);
    			$data['image'] = '/uploads/'.$fileName;
    		}
    	}
    	//执行添加操作
        $data['cateid'] = 62;//$session['cateid'];
    	$res = DB::table('goods') -> insert($data);
    	if($res)
    	{
    		return redirect('business/goods/index') -> with(['info' => '添加成功']); 
    	}else
    	{
    		return back() -> whih(['info' => '添加失败']);
    	}
    }

    //index
    public function index(Request $request)
    {
    	
    	// 查询数据表

		$num = $request -> input('num',10);
    	$goods = DB::table('goods as g1') 
    	   
    		->LeftJoin ('goods as g2','g1.pid','=','g2.id')
    		->select('g1.*','g2.proname as pname',DB::raw("concat(g1.path,',',g1.id) as sort"))
    		
            ->where(function($query) use ($request){
                $query -> where('g1.proname','like','%'.$request -> input('keyword').'%')
                ->where('g1.cateid','62');
            })
        	->orderBy ('sort')
    		->paginate($num);
    		
    		
    		
    		foreach($goods as $k => $v)
    		{
	    		$count = substr_count($v -> path,',');
	    		$str = str_repeat('|-------',$count);

	    		$goods[$k] -> pname = $str.$v -> pname;
	    		if(empty($goods[$k] -> pname))
    			{
    				$goods[$k] -> pname = '父分类';
    			}
    		}
        return view('business.goods.index',['goods'=> $goods,'request' => $request -> all()]);
    }

    //ajaxupdate1
    public function postAjaxUpdate1(Request $request)
    {	
    	$id = $request -> input('id');
    	
        //根据id查询
        $data = DB::table('goods')-> where('id',$id) -> first();

        // 修改是否上架
        if($data -> is_del =='0')
        {
            $res = DB::table('goods')-> where('id',$id) -> update(['is_del'=>'1']); 
            if($res)
            {
                 return response()->json(0);
            }else{
                 return response()->json(1);
            }
        }else
        {
            $res = DB::table('goods')-> where('id',$id) -> update(['is_del'=>'0']); 
            if($res)
            {
                 return response()->json(2);
            }else{
                 return response()->json(3);
            }
        }
      
    }
    //ajaxupdate2
    public function postAjaxUpdate2(Request $request)
    {
    	$id = $request -> input('id');
    	//根据id查询
        $data = DB::table('goods')-> where('id',$id) -> first();
    	  // 修改hot热门
         if($data -> hot =='0')
        {
            $res = DB::table('goods')-> where('id',$id) -> update(['hot'=>'1']); 
            if($res)
            {
                 return response()->json(4);
            }else{
                 return response()->json(5);
            }
        }else
        {
            $res = DB::table('goods')-> where('id',$id) -> update(['hot'=>'0']); 
            if($res)
            {
                 return response()->json(6);
            }else{
                 return response()->json(7);
            }
        }
    }

    //edit
    public function edit($id)
    {
    	 //查询所要修改的分类
    	$array = DB::table('goods') -> where('id',$id) -> first();
    	// dd($array);
        //查询所有的分类
        $data = DB::table('goods')
            -> select(['*',DB::raw("concat(path,',',id) as sort")])
            -> where('cateid',62)//$session['cateid'];
            ->orderBy ('sort','asc')
            ->get();
        // dd($data);
        foreach($data as $k => $v)
        {
            $count = substr_count($v -> path,',');
            $str = str_repeat('|-------',$count);

            $data[$k] -> proname = $str.$v -> proname;
            
        }
    	return view('business.goods.edit',['arr' => $array,'data'=>$data]);
    	
    }

    //update
    public function update(Request $request)
    {
    	//验证错误
    	$this -> validate($request,[

    		'proname' => 'required',
    		'pid'=> 'required',
    		
    		],[
    		'proname.required'=>'商品名不能为空',
    		'pid.required'=>'父类不能为空',
    		]);
    	$data = $request -> except('_token');
    	if($request -> hasFile('image'))
    	{
    		//判断图片是否有效
    		if($request -> file('image') -> isValid())
    		{

    			//获取扩展名
    			$suffix = $request -> file('image') -> getClientOriginalExtension();
    			//随机名称
    			$fileName = time().mt_rand(100000,999999).'.'.$suffix;
    			//移动位置
    			$request -> file('image') -> move('./uploads',$fileName);
    			$data['image'] = '/uploads/'.$fileName; 
    		}
    	}
    	// dd($data);
    	
    	// dd($data);
    	//拼出新的path路径
    	if($data['pid'] == 0)
        {
            $data['path']=0;
            // dd($data);
        }else
        {
             // 根据传来的pid查找父类
            $parent = DB::table('goods')
            -> where('id',$data['pid'])
            -> first();
            // 拼出新加商品的path
            $parentPath = $parent -> path;
            $data['path'] = $parentPath.','.$parent ->id;
            //将cate_id加入到更改后的商品内
    		$data['cateid'] = $parent ->cateid;
    		// dd($data);
    		
        }
        // dd($data);

    	$res = DB::table('goods') -> where ('id',$data['id']) -> update($data);
    	if($res)
    	{
    		return redirect('/business/goods/index') -> with(['info' => '修改成功']);
    	}else
    	{
    		return back() -> with(['info' => '修改失败']);
    	}
    }

    //delete
    public function delete($id)
    {
    	$res = DB::table('goods') -> where('pid',$id) -> first();
    	if($res)
    	{
    		return back() -> with(['info' => '拥有子类不能删除']);
    	}else
    	{
    		$res = DB::table('goods') -> delete($id);
    		if($res)
    		{
    			return redirect('/business/goods/index') -> with(['info' => '删除成功']);
    		}else
    		{
    			return back() -> with(['info' => '删除失败']);
    		}
    	}
    }

    
}




      	